package life.kenny.community.controller;

import com.qcloud.cos.model.PutObjectResult;
import life.kenny.community.dto.FileDTO;
import life.kenny.community.provider.QCloudProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Jay
 * @date 2021/12/9 9:45 上午
 */
@Controller
public class FileController {

    @Value("${qcloud.url.pre}")
    private String urlPre;

    @Autowired
    private QCloudProvider qCloudProvider;

    @RequestMapping("/file/upload")
    @ResponseBody
    public FileDTO upLoad(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("editormd-image-file");
        try {
            PutObjectResult result = qCloudProvider.upload(file);
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(1);
            fileDTO.setUrl(urlPre+file.getOriginalFilename());
            return fileDTO;
        } catch (Exception e) {
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(0);
            fileDTO.setMessage("上传失败");
            return fileDTO;
        }
    }
}
